<?php
/**
 * ============================================================================
 * MXCMall开源商城
 * 官网地址:http://www.mothink.cn
 * 联系QQ:510858687
 * ============================================================================
 * 基础服务类
 */

namespace Api\Model;
use Think\Model;

class BaseModel extends Model {

    /**
     * 用来处理内容中为空的判断
     */
    public function checkEmpty($data, $isDie = false) {
        foreach ($data as $key => $v) {
            if (trim($v) == '') {
                if ($isDie)
                    die("{status:-1,'key'=>'$key'}");
                return false;
            }
        }
        return true;
    }

    /**
     * 输入sql调试信息
     */
    public function logSql($m) {
        echo $m->getLastSql();
    }

    /**
     * 获取一行记录
     */
    public function queryRow($sql) {
        $plist = $this->query($sql);
        return $plist[0];
    }

    /**
     * 将查询来的ID列转为字符
     * @param type $ids
     * @param type $key
     * @return type
     */
    public function idsToString($ids, $key) {
        $str = '';
        foreach ($ids as $v) {
            $str[] = $v[$key];
        }
        return implode(',', $str);
    }

    /**
     * 余额日志
     */
    public function MlogBalance($userId, $price, $logType, $logContent = '') {
        $m = M('log_user_balance');
        $typeName = array(1 => '订单支付', 2 => '充值', 3 => '提现', 4 => '退款', 5 => '转售收益', 6 => '销售收益', 8 => '商家退款', 9 => '退回保证金');
        $data = array();
        $data['userId'] = $userId;
        $userBalance=M("Users")->where("userId={$userId}")->getField("userBalance");
        $data['current_balance'] = $userBalance;
        $data['logContent'] = $logContent;
        $data['price'] = $price;
        $data['logType'] = $logType;
        $data['typeName'] = $typeName[$logType];
        $data['logTime'] = date('Y-m-d H:i:s');
        $rs = $m->add($data);
            
        return $rs;
    }

    public function isFriend($uid, $fuid) {
        $m = M('user_friends');
        $rs = $m->where('uid = ' . $uid . ' AND fuid = ' . $fuid)->getField('type');
        if ($rs > 0)
            return 1;
        return 0;
    }

    public function isFollow($userId, $shopId) {
        $m = M('favorites');

        $rs = $m->where('userId=' . $userId . ' AND shopId=' . $shopId)->getField('id');

        if ($rs > 0)
            return 1;
        return 0;
    }

    /**
     * 好友商店ID
     */
    public function friendShopId($userId) {
        $sql = 'select s.shopId from __PREFIX__user_friends as f left join __PREFIX__shops as s on f.fuid = s.userId where f.type = 2 and f.uid = ' . $userId;
        $shopId = $this->query($sql);
        if (empty($shopId))
            return array();
        $shopIds = array();
        foreach ($shopId as $v) {
            if (!empty($v['shopId']))
                $shopIds[] = $v['shopId'];
        }

        return $shopIds;
    }

    /**
     * 推荐商店ID
     */
    public function recomShopId() {
        $m = M('shops');
        $shopId = $m->where('isRecom = 1 and shopFlag = 1 and shopStatus = 1')->field('shopId')->select();

        if (empty($shopId))
            return array();
        $shopIds = array();
        foreach ($shopId as $v) {
            if (!empty($v['shopId']))
                $shopIds[] = $v['shopId'];
        }

        return $shopIds;
    }

    /**
     * 获取经纬度
     */
    public function getBaiduLonLat($address) {
        $address = urlencode($address);
        $ch = curl_init();
        $url = 'http://api.map.baidu.com/geocoder/v2/?ak=0356025E5F49c57a6899253324d84e49&output=json&address=' . $address;
//        $header = array(
//            'apikey: b1e361ecc709fa77f0f40896bf18c3ca',
//        );
        // 添加apikey到header
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        // 执行HTTP请求
        curl_setopt($ch, CURLOPT_URL, $url);
        $res = curl_exec($ch);
        $res = json_decode($res, TRUE);
        if ($res['status'] == 0) {
            $res = $res['result']['location'];
        }
        return $res;
    }

    /**
     * 获取经纬度
     */
//    public function getBaiduLonLat($address) {
//        $address = urlencode($address);
//        $ch = curl_init();
//        $url = 'http://apis.baidu.com/3023/geo/code?a=' . $address;
//        $header = array(
//            'apikey: b1e361ecc709fa77f0f40896bf18c3ca',
//        );
//        // 添加apikey到header
//        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        // 执行HTTP请求
//        curl_setopt($ch, CURLOPT_URL, $url);
//        $res = curl_exec($ch);
//        $res = json_decode($res, TRUE);
//
//        return $res;
//    }

    /**
     * 获取所有节点商品的ID
     * @param type $goodsId
     */
    public function getNodeGoodsId($goodsId) {
        $isSource = M('goods')->where('goodsId=' . $goodsId)->getField('isSource');
        if ($isSource == 1) {
            $idArr = M('goods_resale')->where('sourceId=' . $goodsId)->field('goodsId')->select();
            $node = $goodsId;
        } else {
            $sourceId = M('goods_resale')->where('goodsId=' . $goodsId)->getField('sourceId');
            $idArr = M('goods_resale')->where('sourceId=' . $sourceId)->field('goodsId')->select();
            $node = $sourceId;
        }

        if (!empty($idArr)) {
            foreach ($idArr as $v) {
                $node .= ',' . $v['goodsId'];
            }
            $node = trim($node, ',');
        }

        return $node;
    }

    /**
     * 获取订单商品最新价格
     * @param type $orderId
     * @return type
     */
    public function getOrderGoods($orderId) {
        $sql = "select o.orderId,o.orderSN,o.orderNo,og.goodsNumber,g.marketPrice,g.shopPrice,g.goodsId,g.goodsSize,g.goodsWeight,g.goodsName,g.goodsThumbs,g.isSource "
                . " from __PREFIX__orders as o left join __PREFIX__order_goods as og on o.orderId = og.orderId "
                . " left join __PREFIX__goods as g on og.goodsId = g.goodsId where o.orderId = " . $orderId;
        $goods = $this->query($sql);
       
        $totalMoney = 0;
        $stotalMoney = 0;
        $sorderNo = 0;
        foreach ($goods as $v) {
            $totalMoney += ($v['shopPrice'] * $v['goodsNumber']);
            M('order_goods')->where('orderId = ' . $orderId . ' and goodsId = ' . $v['goodsId'])->save(array('marketPrice' => $v['marketPrice'], 'shopPrice' => $v['shopPrice']));
            if ($v['isSource'] == 0) {
                $sql = 'select g.* from __PREFIX__goods_resale as gr left join __PREFIX__goods as g on gr.sourceId = g.goodsId where gr.goodsId = ' . $v['goodsId'];
                $sourceGoods = $this->queryRow($sql);
                M('order_goods')->where('orderNo = ' . $v['orderNo'] . ' and goodsId = ' . $sourceGoods['goodsId'])->save(array('marketPrice' => $sourceGoods['marketPrice'], 'shopPrice' => $sourceGoods['shopPrice']));
                $stotalMoney += ($sourceGoods['shopPrice'] * $v['goodsNumber']);
                $sorderNo = $v['orderNo'];
            }
        }

        $rs = M('orders')->where('orderId=' . $orderId)->save(array('totalMoney' => $totalMoney));
        $rs = M('orders')->where('orderSN = 0 AND orderNo =' . $sorderNo)->save(array('totalMoney' => $stotalMoney));

        return array('goods' => $goods, 'totalMoney' => $totalMoney);
    }

    /**
     * 记录店铺访客
     * @param type $shopId
     * @param type $userId
     * @return boolean
     */
    public function logShopHits($shopId, $userId) {
        $m = M('log_shop_hits');
        $data = array();
        $data['ip'] = get_client_ip();
        $data['createTime'] = date('Y-m-d');
        $data['hits'] = 1;
        $data['shopId'] = $shopId;
        $data['userId'] = $userId;

        $isLog = $m->where('createTime = "' . $data['createTime'] . '" and shopId = ' . $shopId . ' and userId = ' . $userId)->count();
        if ($isLog == 0) {
            $rs = $m->add($data);
            return $rs;
        }

        return false;
    }

    /**
     * 记录订单利润
     * @param type $orderId
     */
    public function logUserProfit($orderId, $orderStatus = 0) {
        $m = M('order_goods');
        $goods = $m->where('orderId=' . $orderId)->find();
        $percent = M('sys_configs')->where('fieldCode = "percentage"')->getField('fieldValue');
        $percent = 1 - $percent;

        if ($goods['isSource']) {
            //非转售
            $goodsInfo = M('goods')->where('goodsId = ' . $goods['goodsId'])->find();
            $data = array();
            $data['orderId'] = $orderId;
            $data['goodsId'] = $goods['goodsId'];
            $data['pgoodsId'] = 0;
            $data['shopId'] = $goods['shopId'];
            $data['orderNo'] = $goods['orderNo'];
            $data['shopPrice'] = $goods['shopPrice'];
            $data['pshopPrice'] = 0;
            $data['percent'] = 1;
            $data['profit'] = $goods['shopPrice'] * $goods['goodsNumber'];
            $data['orderStatus'] = $orderStatus;
            $data['isSource'] = $goods['isSource'];
            $data['isSelling'] = $goodsInfo['isSelling'];
            $data['isSale'] = $goodsInfo['isSale'];
            $data['isDel'] = $goodsInfo['isDel'];
            $data['goodsStatus'] = $goodsInfo['goodsStatus'];
           
            $rs = M('log_user_profit')->add($data);
        } else {
            $node = M('goods_resale')->where('goodsId = ' . $goods['goodsId'])->getField('node');
            $goodsAll = M('goods')->where('goodsId in (' . $node . ')')->getField('goodsId,shopPrice,shopId,isSource,isSelling,isSale,isDel,goodsStatus');
            foreach ($goodsAll as $v) {
                $data = array();
                if ($v['isSource']) {
                    $data['orderId'] = $orderId;
                    $data['goodsId'] = $v['goodsId'];
                    $data['pgoodsId'] = 0;
                    $data['shopId'] = $v['shopId'];
                    $data['orderNo'] = $goods['orderNo'];
                    $data['shopPrice'] = $v['shopPrice'];
                    $data['pshopPrice'] = 0;
                    $data['percent'] = 1;
                    $data['profit'] = $v['shopPrice'] * $goods['goodsNumber'];
                    $data['orderStatus'] = $orderStatus;
                    $data['isSource'] = $v['isSource'];
                    $data['isSelling'] = $v['isSelling'];
                    $data['isSale'] = $v['isSale'];
                    $data['isDel'] = $v['isDel'];
                    $data['goodsStatus'] = $v['goodsStatus'];
                    $data['createTime'] = date('Y-m-d H:i:s');

                    $rs = M('log_user_profit')->add($data);
                } else {
                     $data['createTime'] = date('Y-m-d H:i:s');
                    //交易成功，结算的时候，卖家应该收到的是1000元金额。转售商收到的是加价的198元

                    $goodsResale = M('goods_resale')->where('goodsId = ' . $v['goodsId'])->find();
                    $data['orderId'] = $orderId;
                    $data['goodsId'] = $v['goodsId'];
                    $data['pgoodsId'] = $goodsResale['parentId'];
                    $data['shopId'] = $v['shopId'];
                    $data['orderNo'] = $goods['orderNo'];
                    $data['shopPrice'] = $v['shopPrice'];
                    $data['pshopPrice'] = $goodsAll[$goodsResale['parentId']]['shopPrice'];
                    $data['percent'] = $percent;
                    $data['profit'] = (($v['shopPrice'] - $data['pshopPrice'] ) * $goods['goodsNumber']) * $percent;
                    $data['orderStatus'] = $orderStatus;
                    $data['isSource'] = $v['isSource'];
                    $data['isSelling'] = $v['isSelling'];
                    $data['isSale'] = $v['isSale'];
                    $data['isDel'] = $v['isDel'];
                    $data['goodsStatus'] = $v['goodsStatus'];
                    $data['createTime'] = date('Y-m-d H:i:s');
                    
                    $rs = M('log_user_profit')->add($data);
                }
            }
        }
        return;
    }
 
    /**
     * 更新订单相关状态
     * @param type $orderId
     * @param type $orderStatus
     * @return type
     */
    public function upOrderStatus($orderId, $orderStatus) {
        $m = M('orders');
        $rs = $m->where('orderId in (' . $orderId . ')')->save(array('orderStatus' => $orderStatus, 'upTime' => date('Y-m-d H:i:S')));
        $m = M('log_user_profit');
        $rs = $m->where('orderId in (' . $orderId . ')')->save(array('orderStatus' => $orderStatus, 'upTime' => date('Y-m-d H:i:S')));

        return $rs;
    }

    /**
     * 订单利润加入余额
     * @param type $orderId
     * @return type
     */
    public function upProfitToBalance($orderId) {
        $m = M('log_user_profit');
        $profit = $m->where('orderId in (' . $orderId . ') and orderStatus in(-3, 6)')->select();
        foreach ($profit as $v) {
            if ($v['isSource'] == 1) {
                $userId = M('shops')->where('shopId = ' . $v['shopId'])->getField('userId');
                $rs = M('users')->where('userId=' . $userId)->setInc('userBalance', $v['profit']);
                $this->MlogBalance($userId, $v['profit'], 6, '订单完成,销售收益,商品销售金额加入余额');
            } else {
                if ($v['isDel'] == 1 && $v['goodsStatus'] == 1) {
                    $userId = M('shops')->where('shopId = ' . $v['shopId'])->getField('userId');
                    $rs = M('users')->where('userId=' . $userId)->setInc('userBalance', $v['profit']);
                    $this->MlogBalance($userId, $v['profit'], 6, '订单完成,转售收益,商品转售利润加入余额');
                }
            }
        }

        return;
    }

    /**
     * 2天未发货订单自动取消
     * @param type $userId
     */
    public function upNoshiftOrder($userId) {
        $date = date("Y-m-d", strtotime("-2 day"));
        $m = M('orders');
        $orders = $m->where('orderStatus = 0 and orderFlag = 1 and orderSN != 0 and userId = ' . $userId . ' and date_format(`createTime`, "%Y-%m-%d") <= "' . $date . '"')->select();
        foreach ($orders as $v) {
            $totalPrice = $v['totalMoney'] + $v['postage'] + $v['supPrice'] + $v['supPostage'];
            $rs = M('users')->where('userId=' . $userId)->setInc('userBalance', $totalPrice);
            $this->MlogBalance($userId, $totalPrice, 8, '商家未按时发货自动退款');
            $m->where('orderNo = ' . $v['orderNo'])->save(array('orderFlag' => 0));
        }

        return;
    }

    /**
     * 15天完成的订单金额转到余额
     * @param type $userId
     */
    public function upFinishProfitOrder($userId) {
        return false;  //已经转到  curl http://www.yushangcn.com/index.php/Admin/FinishOrder/upFinishALLOrder.html 计划任务内

        $date = date("Y-m-d", strtotime("-8 day"));
        $shopId = M('shops')->where('userId = ' . $userId)->getField('shopId');
        $m = M('log_user_profit');
        $profits = $m->where('profit > 0 and profitStatus = 0 and orderStatus in (-3, 6) and shopId = ' . $shopId . ' and date_format(`createTime`, "%Y-%m-%d") <= "' . $date . '"')->select();
        foreach ($profits as $v) {
            $rs = M('users')->where('userId=' . $userId)->setInc('userBalance', $v['profit']);
            if ($v['isSource'] == 1) {
                $this->MlogBalance($userId, $v['profit'], 6, '订单[' . $v['orderNo'] . ']销售收益');
            } else {
                $this->MlogBalance($userId, $v['profit'], 5, '订单[' . $v['orderNo'] . ']转售收益');
            }
            $m->where('id = ' . $v['id'])->save(array('profitStatus' => 1));
        }
    }

    /**
     * 3天后自动完成订单
     * @param type $userId
     */
    public function _upOrderToFinish($userId) {
        $m = M('orders');
        $date = date("Y-m-d", strtotime("-3 day"));
        $noFinishOrder = $m->where('orderStatus = 2 and userId = ' . $userId . ' and date_format(`createTime`, "%Y-%m-%d") <= "' . $date . '"')->field('orderId, orderNo, orderSN, date_format(`createTime`, "%Y-%m-%d") AS time ')->select();
        $noFinishOrderId = '';
        foreach ($noFinishOrder as $v) {
            $noFinishOrderId .= $v['orderNo'] . ',';
        }
        $noFinishOrderId = trim($noFinishOrderId, ',');
        if (!empty($noFinishOrderId)) {
            $rs = $this->upOrderNoStatus($noFinishOrderId, 6);
        }
        $shopId = M('shops')->where('userId = ' . $userId)->getField('shopId');
        if ($shopId > 0) {
            $_noFinishOrder = $m->where('orderStatus = 2 and shopId = ' . $shopId . ' and date_format(`createTime`, "%Y-%m-%d") <= "' . $date . '"')->field('orderId, orderNo, orderSN, date_format(`createTime`, "%Y-%m-%d") AS time ')->select();
            $_noFinishOrderId = '';
            foreach ($_noFinishOrder as $v) {
                $_noFinishOrderId .= $v['orderNo'] . ',';
            }
            $_noFinishOrderId = trim($_noFinishOrderId, ',');
            if (!empty($_noFinishOrderId)) {
                $rs = $this->upOrderNoStatus($_noFinishOrderId, 6);
            }
        }
    }

    /**
     * 更新订单相关状态
     * @param type $orderId
     * @param type $orderStatus
     * @return type
     */
    public function upOrderNoStatus($orderNo, $orderStatus) {
        $m = M('orders');
        $rs = $m->where('orderNo in (' . $orderNo . ')')->save(array('orderStatus' => $orderStatus, 'upTime' => date('Y-m-d H:i:S')));
        $m = M('log_user_profit');
        $rs = $m->where('orderNo in (' . $orderNo . ')')->save(array('orderStatus' => $orderStatus, 'upTime' => date('Y-m-d H:i:S')));

        return $rs;
    }

    function randpw($len=8,$format='ALL'){
        $is_abc = $is_numer = 0;
        $password = $tmp ='';  
        switch($format){
        case 'ALL':
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        break;
        case 'CHAR':
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
        break;
        case 'NUMBER':
        $chars='123456789';
        break;
        default :
        $chars='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
        break;
        }

        $password=''; 
        while(strlen($password)<$len) 
        $password.=substr($chars,(mt_rand()%strlen($chars)),1); 
        return $password; 

    }
    
}
?>